<script setup name="upload">
import { onMounted, ref, watch } from 'vue'
import { delAlone, getAllFatherFile } from '@/services/upload.js'
import { useNotePageStore, useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
let noteStore = useNotePageStore()
let userStore = useUserStore()

onMounted(async () => {
  // 刷新页面后，获取已上传图片的信息
  if (noteStore.fatherFiled) {
    let res = await getAllFatherFile(noteStore.fatherFiled)
    res.data.forEach((ele) => {
      fileList.value.push({ name: ele.file_name, url: ele.alone, id: ele.id })
    })
  }
})

// 监听父组件是否要删除父级文件夹
watch(
  () => noteStore.empty,
  () => {
    // 清空
    fileList.value = []
  }
)

watch(
  () => noteStore.upIsOk,
  () => {
    // 清除当前父级文件夹数据
    noteStore.setFatherFiled('')
    fileList.value = []
  }
)

const fileList = ref([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // }
])

// 图片预览需要使用此
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 检查是否是重复的文件
const decisionRepetition = (e) => {
  // proxy 是个伪数组，要求即构成
  // 返回值很确定是否上传
  return [...fileList.value].findIndex((ele) => ele.name === e.name) === -1
    ? true
    : false
}

// 图片预览
// 点击了已经上传的文件的时候触发
const handlePictureCardPreview = (uploadFile) => {
  // 就让文件触发预览的组件
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

// 文件列表移除文件时的钩子
const handleRemove = async (uploadFile) => {
  // 拿到要删除的文件，去后台删除真实的照片
  // 有response就用response的，没有就用有id的
  // 由于，上传重复图片会被检测出来，但是仍然会触发移除文件的钩子，所以可以通过response去判断是否上传过的图片
  try {
    if (uploadFile.response) {
      // 是已经上传过的图片，进行删除
      await delAlone(uploadFile.response.data.id)
      ElMessage({
        message: '删除成功！',
        type: 'success'
      })
    } else {
      // 传递id去删除图片
      await delAlone(uploadFile.id)
    }
  } catch (error) {
    ElMessage.error('图片已经在后端删除!')
  }
}

// 上传成功的钩子
// 每上传一个文件都会触发一次
const upLoadImgSuccess = (response) => {
  // 如果是 20060, 可能是轮询把父级文件夹给删了，那么要清空当前绑定的数据
  if (response.code === 20060) {
    // 清除当前父级文件夹数据
    noteStore.setFatherFiled('')
    fileList.value = []
    return ElMessage({
      message: response.msg + ',请重新绑定!',
      type: 'warning'
    })
  }
}

// 图片上传失败的钩子
const errfb = () => {
  ElMessage.error('上传失败！')
}

// 要设置请求头的token
let tokenHead = ref('')
if (userStore.tokenObj && userStore.tokenObj.token) {
  tokenHead.value = userStore.tokenObj.token
}
</script>
<template>
  <div
    class="upload-img-box scrollBarDiv clearfix"
    v-if="noteStore.fatherFiled"
  >
    <!-- action="http://localhost:9000/note/upload/dan" -->
    <el-upload
      v-model:file-list="fileList"
      action="http://zengzhi.info:9000/note/upload/dan"
      :data="{ folder: noteStore.fatherFiled }"
      :headers="{ Authorization: tokenHead }"
      name="files"
      multiple
      method="post"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="upLoadImgSuccess"
      :on-error="errfb"
      :before-upload="decisionRepetition"
    >
      <el-icon>
        <SvgIcon href="#icon-note-tubiaolunkuo-"></SvgIcon>
      </el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="母鸡哦！" />
    </el-dialog>
  </div>
  <div class="upload-img-box scrollBarDiv clearfix special" v-else>
    <div class="lock">
      <SvgIcon href="#icon-note-bangding"></SvgIcon>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.upload-img-box {
  margin-left: 50%;
  margin-top: 10px;
  padding: 10px;
  transform: translateX(-50%);
  width: 85%;
  min-width: 1110px;

  height: 84vh;
  background-color: #f9f9fa;
  border-radius: 10px;
  overflow-y: scroll;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.special {
  position: relative;
  .lock {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-size: 104px;
    color: var(--el-color-info-light-5);
  }
}

.special:hover {
  cursor: no-drop;
}
</style>
